package com.sa.iam.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 令牌传递的拦截器
 * @author Architecture Station
 * @version 1.0
 */
//@Component
public class TokenPassingInterceptor implements RequestInterceptor {

    /**
     * 将原有请求中的令牌取出，并添加到新的请求中
     * @param requestTemplate 新请求模板
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获得原有的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        String token = requestAttributes.getRequest().getHeader("satoken");
//        if (token != null) {
//            // 将令牌添加到新的请求中
//            requestTemplate.header("satoken", token);
//        }

        // 将原有请求中所有的请求头添加到新的请求模板中
        if(requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            request.getHeaderNames().asIterator().forEachRemaining(headerName -> {
                requestTemplate.header(headerName, request.getHeader(headerName));
            });
        }
    }
}















